package com.xht.resource;

import cn.hutool.core.util.ArrayUtil;
import com.xht.component.PermitAllUrlProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.util.CollectionUtils;

/**
 * <h1>描述 ：</h1>
 *
 * @author : 小糊涂
 * @version : 1.0
 **/
@Slf4j
@EnableWebSecurity
@RequiredArgsConstructor
public class ResourceServerConfiguration {

    private final PermitAllUrlProperties permitAllUrlProperties;

    private final OpaqueTokenIntrospector opaqueTokenIntrospector;

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 所有请求都进行拦截
        if (!CollectionUtils.isEmpty(permitAllUrlProperties.getGetUrls())) {
            http.authorizeRequests().mvcMatchers(HttpMethod.GET, ArrayUtil.toArray(permitAllUrlProperties.getGetUrls(), String.class)).permitAll();
        }
        if (!CollectionUtils.isEmpty(permitAllUrlProperties.getPostUrls())) {
            http.authorizeRequests().mvcMatchers(HttpMethod.POST, ArrayUtil.toArray(permitAllUrlProperties.getPostUrls(), String.class)).permitAll();
        }
        if (!CollectionUtils.isEmpty(permitAllUrlProperties.getDeleteUrls())) {
            http.authorizeRequests().mvcMatchers(HttpMethod.DELETE, ArrayUtil.toArray(permitAllUrlProperties.getDeleteUrls(), String.class)).permitAll();
        }
        if (!CollectionUtils.isEmpty(permitAllUrlProperties.getPutUrls())) {
            http.authorizeRequests().mvcMatchers(HttpMethod.PUT, ArrayUtil.toArray(permitAllUrlProperties.getPutUrls(), String.class)).permitAll();
        }
        http.authorizeRequests().mvcMatchers(ArrayUtil.toArray(permitAllUrlProperties.getAllUrls(), String.class)).permitAll()
                .anyRequest().authenticated()
                // 关闭session
                .and().sessionManagement().disable()
                // 配置资源服务器的无权限，无认证拦截器等 以及JWT验证
                .exceptionHandling()
                //.authenticationEntryPoint()//认证授权异常处理
                //.accessDeniedHandler()//认证成功处理器
                .and()
                .oauth2ResourceServer(resourceServer->{
                    resourceServer.opaqueToken(opaqueTokenConfigurer -> opaqueTokenConfigurer.introspector(opaqueTokenIntrospector));
                }) //资源服务器配置
                .headers().frameOptions().disable().and().csrf().disable().formLogin().disable();
        return http.build();
    }

}
